package com.ruoyi.merchant.service.impl;

import com.ruoyi.merchant.domain.AutoAcceptLog;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.domain.Order;
import com.ruoyi.merchant.mapper.AutoAcceptLogMapper;
import com.ruoyi.merchant.mapper.MerchantMapper;
import com.ruoyi.merchant.mapper.OrderMapper;
import com.ruoyi.merchant.service.IAutoAcceptService;
import com.ruoyi.merchant.service.IOrderService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自动接单Service业务层处理
 */
@Service
public class AutoAcceptServiceImpl implements IAutoAcceptService {

    private static final Logger log = LoggerFactory.getLogger(AutoAcceptServiceImpl.class);

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private AutoAcceptLogMapper autoAcceptLogMapper;

    @Override
    public void executeAutoAccept() {
        log.info("开始执行自动接单任务...");

        try {
            // 1. 查询所有开启自动接单的商家
            List<Merchant> merchants = merchantMapper.selectAutoAcceptMerchants();
            
            if (merchants.isEmpty()) {
                log.info("没有开启自动接单的商家，跳过任务");
                return;
            }

            log.info("共有 {} 个商家开启了自动接单", merchants.size());

            int totalProcessed = 0;
            int totalSuccess = 0;
            int totalFailed = 0;

            // 2. 遍历每个商家
            for (Merchant merchant : merchants) {
                Long merchantId = merchant.getMerchantId();
                Integer estimatedMin = merchant.getAutoAcceptTime();

                // 3. 查询该商家的待接单订单（status=0 且 payment_status=1）
                List<Order> pendingOrders = orderMapper.selectMerchantOrderList(
                    merchantId,
                    0,  // status=0 待接单
                    1,  // payment_status=1 已支付
                    null, null, null, null
                );

                if (pendingOrders.isEmpty()) {
                    continue;
                }

                log.info("商家[{}]有 {} 个待接单订单", merchantId, pendingOrders.size());

                // 4. 自动接单
                for (Order order : pendingOrders) {
                    totalProcessed++;
                    
                    try {
                        // 模拟商家身份调用接单接口
                        // 注意：这里需要在接单方法中临时切换商家ID，或者创建一个内部方法
                        int result = acceptOrderInternal(order.getOrderId(), merchantId, estimatedMin);
                        
                        if (result > 0) {
                            totalSuccess++;
                            log.info("自动接单成功：订单号={}, 商家ID={}", order.getOrderNo(), merchantId);
                            
                            // 记录成功日志
                            saveLog(merchantId, order.getOrderId(), order.getOrderNo(), 1, null);
                        } else {
                            totalFailed++;
                            log.error("自动接单失败：订单号={}, 商家ID={}", order.getOrderNo(), merchantId);
                            
                            // 记录失败日志
                            saveLog(merchantId, order.getOrderId(), order.getOrderNo(), 0, "接单失败");
                        }
                    } catch (Exception e) {
                        totalFailed++;
                        log.error("自动接单异常：订单号={}, 商家ID={}, 错误={}", 
                            order.getOrderNo(), merchantId, e.getMessage(), e);
                        
                        // 记录异常日志
                        saveLog(merchantId, order.getOrderId(), order.getOrderNo(), 0, e.getMessage());
                    }
                }
            }

            log.info("自动接单任务完成：处理{}个订单，成功{}个，失败{}个", 
                totalProcessed, totalSuccess, totalFailed);

        } catch (Exception e) {
            log.error("自动接单任务执行异常", e);
        }
    }

    /**
     * 内部接单方法（不需要验证商家ID）
     */
    private int acceptOrderInternal(Long orderId, Long merchantId, Integer estimatedMin) {
        // 验证订单
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!merchantId.equals(order.getMerchantId())) {
            throw new RuntimeException("订单不属于该商家");
        }
        if (order.getStatus() != 0) {
            throw new RuntimeException("订单状态不正确");
        }
        if (order.getPaymentStatus() != 1) {
            throw new RuntimeException("订单未支付");
        }

        // 更新订单状态
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setMerchantId(merchantId);
        updateOrder.setStatus(1);
        updateOrder.setEstimatedReadyMin(estimatedMin);

        int result = orderMapper.updateOrder(updateOrder);

        // 自动打印订单（如果有默认打印机且开启自动打印）
        if (result > 0) {
            try {
                // 这里需要调用打印逻辑，但要注意不要抛出异常影响接单
                // autoPrintOrder(orderId, merchantId);
            } catch (Exception e) {
                log.error("自动打印失败：订单号={}", order.getOrderNo(), e);
            }
        }

        return result;
    }

    /**
     * 保存自动接单日志
     */
    private void saveLog(Long merchantId, Long orderId, String orderNo, Integer result, String errorMessage) {
        try {
            AutoAcceptLog log = new AutoAcceptLog();
            log.setMerchantId(merchantId);
            log.setOrderId(orderId);
            log.setOrderNo(orderNo);
            log.setAcceptResult(result);
            log.setErrorMessage(errorMessage);
            autoAcceptLogMapper.insertLog(log);
        } catch (Exception e) {
            // 日志保存失败不影响主流程
            AutoAcceptServiceImpl.log.error("保存自动接单日志失败", e);
        }
    }

    @Override
    public List<AutoAcceptLog> selectLogList(String startTime, String endTime) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        return autoAcceptLogMapper.selectLogList(merchantId, startTime, endTime);
    }
}
